package sg.edu.nus.iss.vmcs.customer;

import java.util.ArrayList;

import sg.edu.nus.iss.vmcs.store.CashStore;
import sg.edu.nus.iss.vmcs.store.Coin;
import sg.edu.nus.iss.vmcs.store.Store;
//commented by sandi
import sg.edu.nus.iss.vmcs.store.StoreItem;
import sg.edu.nus.iss.vmcs.util.VMCSException;

public class CoinReceiver {
	
	private TransactionController tCtrl;
	private Integer total_inserted;
	private ArrayList<Coin> coins;
	
	public CoinReceiver(TransactionController tCtrl){
		this.tCtrl=tCtrl;
		
		total_inserted=0;
		coins=new ArrayList<Coin>();
	}
	
	public TransactionController getTransactionController() {
		return tCtrl;
	}
	
	public void startReceive(){
		this.getTransactionController().getCustomerPanel().getCoinInputBox().setActive(true);
		this.total_inserted=0;
		coins.clear();
	}
	
	public void receiveCoin(int weight){
		CustomerPanel cPanel=this.tCtrl.getCustomerPanel();
		CoinInputBox cInputBox=cPanel.getCoinInputBox();
		
		//Reset the display
		cPanel.getInvalidCoinDisplay().setState(false);
		cPanel.getCollectCoinDisplay().setValue("");
		cInputBox.setActive(false);
		
		//Check whether enter coin is valid or not
		CashStore cStore=(CashStore)this.tCtrl.getMainController().getStoreController().getStore(Store.CASH);
		Coin coin=cStore.findCoin(weight);
		if(coin!=null){ //If valid
			coins.add(coin);
			//Calculate the total money so far inserted
			this.total_inserted=this.total_inserted + coin.getValue();
			//Update the display
			cPanel.getTotalMoneyDisplay().setValue(this.total_inserted);
		}
		else{ //If not valid
			cPanel.getInvalidCoinDisplay().setState(true);
		}
		
		//Check whether sufficient money has been inserted
		this.tCtrl.processMoneyReceived(this.total_inserted);		
	}
	
	public void continueReceive(){
		this.tCtrl.getCustomerPanel().getCoinInputBox().setActive(true);
	}
	
	public Boolean storeCash(){
		Boolean result=true;
		try{
			for(Coin c:this.coins)
				this.tCtrl.getMainController().getMachineryController().storeCoin(c);
		}catch(VMCSException e){
			result=false;
		}	
		this.tCtrl.getCustomerPanel().getTotalMoneyDisplay().setValue("");
		return result;
	}
	
	public void stopReceive(){
		tCtrl.getCustomerPanel().getCoinInputBox().setActive(false);
	}
	
	
	public void refundCash(){
		if (total_inserted==0)
			return;
		else {
			
			tCtrl.getCustomerPanel().getCollectCoinDisplay().setValue(total_inserted);
			tCtrl.getCustomerPanel().getTotalMoneyDisplay().setValue("");
			tCtrl.getCustomerPanel().getInvalidCoinDisplay().setState(false);
			total_inserted=0;
			coins.clear();
		}
    }
	
	public void setActive(Boolean st){
		this.getTransactionController().getCustomerPanel().getCoinInputBox().setActive(st);
	}
	
	public Integer getTotalInserted(){
		return this.total_inserted;
	}

}
